<script setup lang="ts">
import {useStore} from "vuex";
// @ts-ignore
import * as echarts from "echarts";
import {nextTick, onBeforeMount, reactive, ref, toRaw, UnwrapRef} from "vue";
import http from "@/http";
// @ts-ignore
import moment from 'moment';
import type {FormRules, FormInstance} from 'element-plus'
import {ElMessage} from 'element-plus'

const store = useStore();

const aa = () => {
  store.state.isCollpace = !store.state.isCollpace
}

// 部门数据
let deptList = ref([])

// 时间转换
let timeUpdate = (time: any) => {
  return moment(time).format('YYYY-MM-DD HH:mm:ss')
}
//  状态
let status = (state: any) => {
  if (state == 0) {
    return '正常'
  } else {
    return '停用'
  }
}

onBeforeMount(() => {
  deptSelectList()
})

//  部门查询
let deptSelectList = () => {
  http.post('/sysdept/select').then(requsest => {
    deptList.value = requsest.data
  })
}
//  查询参数
let queryParams = ref({
  deptName: undefined,
  status: undefined
})

let DeptStatus = [
  {
    id: 0,
    name: '正常'
  },
  {
    id: 2,
    name: '停用'
  }
]

// 搜索按钮
let handleAdd = () => {
  http.post('/sysdept/selectLike', queryParams.value).then(requsest => {
    deptList.value = requsest.data
  })
}

// 重置按钮
let resetQuery = (queryParams: UnwrapRef<{ deptName: undefined; status: undefined }>) => {
  queryParams.deptName = undefined
  queryParams.status = undefined
  deptSelectList()
}


//  弹出层
let dialogVisible = ref(false)
let title = ref(null)


let addScope = (row: any) => {
  // @ts-ignore
  title.value = "添加部门"
  dialogVisible.value = true
  selectDisbled.value = false
  if (row != undefined) {
    deptFroms.parentId = row.deptId
    deptParentStatus.value = row.status
  }
}

let selectDisbled = ref()

let updateScope = (row: any) => {
  // @ts-ignore
  title.value = "修改部门"
  dialogVisible.value = true
  deptParentStatus.value = row.status
  updateById.value = row.deptId
  parentId.value = row.parentId
  if (row.parentId == 0) {
    selectDisbled.value = true
  } else {
    selectDisbled.value = false
  }
  nextTick(() => {
    Object.assign(deptFroms, row)
  })

}

//  部门树形菜单
const defaultProps = {
  children: 'children',
  label: 'deptName',
}


//  表单数据类型
interface RuleDeptForm {
  deptId: number,
  parentId: string,
  deptName: string,
  orderNum: string,
  leader: string,
  phone: string,
  email: string,
  status: string
}

// 表单数据
let deptFroms = reactive<RuleDeptForm>({
  deptId: 0,
  parentId: '',
  deptName: '',
  orderNum: '',
  leader: '',
  phone: '',
  email: '',
  status: '0'
})
//  表单验证
const ruleFormRef = ref<RuleDeptForm>()
const rules = reactive<FormRules<RuleDeptForm>>({
  parentId: [
    {required: true, message: '上级部门不能为空', trigger: 'blur'},
  ],
  deptName: [
    {required: true, message: '部门名称不能为空', trigger: 'change'},
  ],
  orderNum: [
    {required: true, message: '排序方式不能为空', trigger: 'change'},
  ],
  leader: [
    {required: true, message: '负责人不能为空', trigger: 'change'},
  ],
  phone: [
    {required: true, message: '联系电话不能为空', trigger: 'blur'},
  ]
})

//  表单提交
let submitDept = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 修改操作
      if (deptFroms.deptId != 0) {
        deptUpdate()
      } else {
        deptAdd()
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}


let deptParentStatus = ref()

// select选中
let sendTree = (val: any) => {
  //  新增前查询
  http.post('/sysdept/selectById', {deptId: val}).then(request => {
    deptParentStatus.value = request.data[0].status
  })
}

// 新增操作
let deptAdd = () => {
  if (deptParentStatus.value == '1') {
    // @ts-ignore
    ElMessage({message: '部门停用,不允许新增', type: 'error'})
  } else {
    http.post('/sysdept/deptAdd', deptFroms).then(request => {
      // @ts-ignore
      if (request.code == 200) {
        // @ts-ignore
        ElMessage({message: request.msg, type: 'success'})
        dialogVisible.value = false
        deptSelectList()
      }
    })
  }
}


let updateById = ref()
let statusArr = reactive([])
let parentId = ref()
let deptUpdate = () => {
  statusArr = []
  //  修改前查询
  if (deptFroms.status == '1') {
    http.post('/sysdept/SelectParentById', {parentId: updateById.value}).then(request => {
      for (const val of request.data) {
        // @ts-ignore
        statusArr.push(val.status)
      }
      // @ts-ignore
      if (statusArr.includes('0')) {
        // @ts-ignore
        ElMessage({message: '该部门包含未停用的子部门', type: 'error'})
      } else {
        updateDept()
      }
    })
  } else {

    if (parentId.value != 0) {
      http.post('/sysdept/selectById', {deptId: parentId.value}).then(request => {
        if (request.data[0].status == 1) {
          updateDept()
          updateParentStatus(parentId.value)
        } else {
          updateDept()
        }
      })
    } else {
      updateDept()
    }

  }
}

let updateParentStatus = (pid: any) => {
  http.post('/sysdept/updateDept', {deptId: pid, status: 0})
}

let updateDept = () => {
  http.post('/sysdept/updateDept', {
    deptId: deptFroms.deptId,
    parentId: deptFroms.parentId,
    deptName: deptFroms.deptName,
    orderNum: deptFroms.orderNum,
    leader: deptFroms.leader,
    phone: deptFroms.phone,
    email: deptFroms.email,
    status: deptFroms.status
  }).then(request => {
    // @ts-ignore
    if (request.code == 200) {
      // @ts-ignore
      ElMessage({message: request.msg, type: 'success'})
      dialogVisible.value = false
      deptSelectList()
    }
  })
}

// 删除弹出层
let removeDialog = ref(false)
let deptNames = ref()
let deptId = ref()
let childrens = ref()

let deleteScope = (row: any) => {
  removeDialog.value = true
  deptNames.value = row.deptName
  deptId.value = row.deptId
  childrens.value = row.children.length
}

//  删除
let removeTrue = () => {
  if (childrens.value != 0) {
    // @ts-ignore
    ElMessage({message: '存在下级部门,不允许删除', type: 'error'})
    removeDialog.value = false
  } else {
    http.post('/sysdept/removeById', {deptId: deptId.value}).then(request => {
      // @ts-ignore
      if (request.code == 200) {
        // @ts-ignore
        ElMessage({message: request.msg, type: 'success'})
        removeDialog.value = false
        deptSelectList()
      }
    })
  }
}


// 表单重置
let resetForm = () => {
  // @ts-ignore
  ruleFormRef.value?.resetFields()
}

</script>

<template>

  <div>
    <!--   导航区   -->
    <div class="a1">
      <el-icon size="23" @click="aa">
        <Fold/>
      </el-icon>
      <div style="display: inline-block;margin-left: 10px;position: absolute;margin-top: 7px">
        <el-icon size="18" color="dodgerblue">
          <HomeFilled/>
        </el-icon>
      </div>
      <div style="display: inline-block;margin-bottom: 5px;margin-left: 30px;margin-top: 10px">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item></el-breadcrumb-item>
          <el-breadcrumb-item><span style="font-size: 13px;color: black">系统管理</span></el-breadcrumb-item>
          <el-breadcrumb-item><span style="font-size: 12px;color: gray">部门管理</span></el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>

    <div>
      <!-- 搜索框   -->
      <div class="section_search">
        <el-form :model="queryParams" ref="queryForm" :inline="true">
          <div class="searchBach">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="queryParams.deptName" class="search_input" placeholder="请输入部门名称"/>
            </el-form-item>
          </div>
          <div class="searchBach">
            <el-form-item label="状态" prop="status">
              <el-select clearable v-model="queryParams.status" style="width: 190px;" placeholder="部门状态">
                <el-option v-for="dict in DeptStatus"
                           :key="dict.id"
                           :label="dict.name"
                           :value="dict.id"/>
              </el-select>
            </el-form-item>
          </div>
          <div class="searchBach">
            <el-form-item>
              <el-button class="search_button" type="primary" plain @click="handleAdd()">
                <el-icon style="margin-right: 5px">
                  <Search/>
                </el-icon>
                搜索
              </el-button>
              <el-button class="search_button" type="info" plain @click="resetQuery(queryParams)">
                <el-icon style="margin-right: 5px">
                  <Refresh/>
                </el-icon>
                重置
              </el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>

      <!--  新增按钮       -->
      <div style="margin-left: 10px; margin-top: 10px">
        <el-button @click="addScope()" class="search_button" type="primary">
          <el-icon style="margin-right: 5px">
            <Plus/>
          </el-icon>
          新增
        </el-button>
      </div>

      <!--    表格数据区-->
      <div style="width: 100%; margin-top: 10px">
        <el-table
            :data="deptList"
            row-key="deptId"
            :header-cell-style="{'background-color':'whitesmoke','color':'#58626b'}"
            :row-style="{'height':'50px','font-size':'13px'}"
            :tree-props="{ children: 'children'}"
        >
          <!--          default-expand-all-->
          <!--          <el-table-column prop="deptId" label="部门编号" align="left" width="100px"></el-table-column>-->
          <el-table-column prop="deptName" label="部门名称" align="left"></el-table-column>
          <el-table-column prop="orderNum" label="排序方式" align="center" width="100"></el-table-column>
          <el-table-column prop="leader" label="负责人" align="center"></el-table-column>
          <el-table-column prop="phone" label="联系电话" align="center"></el-table-column>
          <el-table-column prop="status" label="部门状态" align="center">
            <template #default="scope">
              <span>{{ status(scope.row.status) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center">
            <template #default="scope">
              <span style="margin-left: 10px">{{ timeUpdate(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="300">
            <template #default="scope">
              <el-button size="mini" type="text" @click="addScope(scope.row)">
                <el-icon style="margin-right: 5px">
                  <Plus/>
                </el-icon>
                新增
              </el-button>
              <el-button size="mini" type="text" @click="updateScope(scope.row)">
                <el-icon style="margin-right: 5px">
                  <Edit/>
                </el-icon>
                修改
              </el-button>
              <el-button v-if="scope.row.parentId != 0" @click="deleteScope(scope.row)" size="mini" type="text">
                <el-icon style="margin-right: 5px">
                  <Delete/>
                </el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>

        </el-table>


      </div>
    </div>

  </div>

  <!--  新增、修改按钮弹出框-->
  <el-dialog v-model="dialogVisible" :title="title" @close="resetForm()" width="600">
    <el-form ref="ruleFormRef"
             :rules="rules"
             status-icon
             :model="deptFroms"
             label-width="auto" style="height: 300px">
      <el-form-item v-show="false" label="部门编号" prop="deptId">
        <el-input v-model="deptFroms.deptId"/>
      </el-form-item>
      <div class="from_back">
        <el-form-item label="上级部门" prop="parentId"
                      style="margin-top: 20px; padding-top: 14px; padding-left: 15px; padding-right: 15px">
          <el-tree-select
              v-model="deptFroms.parentId"
              :data="deptList"
              :props="defaultProps"
              value-key="deptId"
              check-strictly
              :disabled="selectDisbled"
              @change="sendTree"
              placeholder="选择上级部门"
          />
        </el-form-item>
      </div>
      <div class="from_back" style="width: 283px; display: inline-block">
        <el-form-item label="部门名称" prop="deptName"
                      style="padding-top: 14px; padding-left: 15px; padding-right: 15px">
          <el-input v-model="deptFroms.deptName" style="width: 200px" placeholder="请输入部门名称"/>
        </el-form-item>
      </div>
      <div class="from_back" style="width: 283px; display: inline-block">
        <el-form-item label="显示排序" prop="orderNum"
                      style="padding-top: 14px; padding-left: 15px; padding-right: 15px">
          <el-space>
            <el-input-number v-model="deptFroms.orderNum" min="0" controls-position="right"/>
            <template #decrease-icon>
              <el-icon>
                <Minus/>
              </el-icon>
            </template>
          </el-space>
        </el-form-item>
      </div>
      <div class="from_back" style="width: 283px; display: inline-block">
        <el-form-item label="负责人" prop="leader" style="padding-top: 14px; padding-left: 15px; padding-right: 15px">
          <el-input v-model="deptFroms.leader" style="width: 200px" placeholder="请输入负责人"/>
        </el-form-item>
      </div>
      <div class="from_back" style="width: 283px; display: inline-block">
        <el-form-item label="联系电话" prop="phone" style="padding-top: 14px; padding-left: 15px; padding-right: 15px">
          <el-input v-model="deptFroms.phone" style="width: 200px" placeholder="请输入联系电话"/>
        </el-form-item>
      </div>
      <div class="from_back" style="width: 283px; display: inline-block">
        <el-form-item label="邮箱" prop="email" style="padding-top: 14px; padding-left: 15px; padding-right: 15px">
          <el-input v-model="deptFroms.email" style="width: 200px" placeholder="请输入邮箱"/>
        </el-form-item>
      </div>
      <div class="from_back" style="width: 283px; display: inline-block">
        <el-form-item label="部门状态" style="padding-top: 14px; padding-left: 15px; padding-right: 15px">
          <el-radio-group v-model="deptFroms.status" class="ml-4" style="margin-top: -4px">
            <el-radio label="0" size="large">正常</el-radio>
            <el-radio label="1" size="large">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>

      <div class="dialog-footer" style="float: right;margin-top: 20px ">
        <el-button type="primary" @click="submitDept(ruleFormRef)">
          确定
        </el-button>
        <el-button @click="dialogVisible=false">取消</el-button>
      </div>


    </el-form>
  </el-dialog>

  <!--  删除弹出框-->
  <el-dialog v-model="removeDialog" title="警告" width="500" style="height: 160px;margin-top: 240px;font-weight: bold">
    <div style="font-weight: lighter; margin-top: 12px">
      <el-icon size="24px" color="#e4b53d" style="vertical-align: -5px;">
        <WarningFilled/>
      </el-icon>
      是否确认删除名称为" {{ deptNames }} "的数据项?
    </div>
    <template #footer>
      <div class="dialog-footer" style="margin-top: 6px">
        <el-button type="primary" @click="removeTrue()">确定</el-button>
        <el-button @click="removeDialog=false">取消</el-button>
      </div>
    </template>
  </el-dialog>

</template>


<style scoped lang="scss">
.a1 {
  width: 100%;
  height: 50px;
}

.section_search {
}

.searchBach {
  border-radius: 10px;
  display: inline-block;
  line-height: 65px;
  height: 52px;
  padding-left: 25px;
}

.searchBach:hover {
  background: aliceblue;
}

.search_input {
  height: 32px;
  width: 200px;
}

.search_button {
  width: 80px;
  height: 32px;
  font-size: 13px;
}

.from_back {
  border-radius: 10px;
  height: 60px;
}

.from_back:hover {
  background: aliceblue;
}


::v-deep .el-table__body {
  //-webkit-border-horizontal-spacing: 13px;  // 水平间距
  -webkit-border-vertical-spacing: 10px; // 垂直间距
}

::v-deep .el-table, .el-table__expanded-cell {
  background-color: transparent
}

.el-button {
  font-size: 13px;
}

</style>



